<?php
/**
 * Created by PhpStorm.
 * User: Admin
 * Date: 2018/5/31
 * Time: 11:13
 */

namespace App\Repository;


use App\Exceptions\BusinessException;
use App\Exceptions\ValidatorException;
use App\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;

class AuthRepository
{
    /**
     * 登录
     *
     * @param array $data
     * @return AuthRepository|\Illuminate\Database\Eloquent\Model|null|object
     * @throws ValidatorException
     */
    public function loginByFrom(array $data)
    {
        $this->validator($data);


        $user = $this->getUserByPhone($data['phone']);

        if (!$user) {
            throw new BusinessException(BusinessException::PARAMETER_ERROR, '手机号码不存在');
        }

        if (!Hash::check($data['password'], $user->password)) {
            throw new BusinessException(BusinessException::PARAMETER_ERROR, '密码不正确');
        }

        $user->token = $user->createToken('Authorization')->accessToken;

        return $user;
    }

    /**
     * 修改密码
     *
     * @param string $password
     * @param string $newPassword
     * @return string
     */
    public function changePassword(string $password, string $newPassword) {
        $user = \auth()->user();
        if (!Hash::check($password, $user->password)) {
            throw new BusinessException(BusinessException::PARAMETER_ERROR, '原密码不正确');
        }

        $user->password = Hash::make($newPassword);
        $user->save();

        return '修改成功';
    }

    /**
     * 表单验证
     * @param array $data
     * @throws ValidatorException
     * @return boolean
     */
    private function validator(array $data)
    {
        $validator =   Validator::make($data, [
            'phone' => [
                'required',
                'regex:/^1[345789][0-9]{9}$/',
                'numeric'
            ],
            'password' => 'required'
        ], [
            'required' => ':attribute 不能为空',
            'numeric' => ':attribute 不正确',
            'regex' => ':attribute 格式不对',
        ], [
            'phone' => '手机号码',
            'password' => '登录密码'
        ]);

        if ($validator->fails()) {
            throw new ValidatorException($validator);
        }

        return true;
    }

    /**
     * 通过手机号查找用户
     * @param string $phone
     * @return \Illuminate\Database\Eloquent\Model|null|object|static
     */
    public function getUserByPhone(string $phone)
    {
        return User::query()->where('phone', $phone)->first();
    }

    /**
     * get open by code
     *
     * @param string $code
     * @return array|\Illuminate\Database\Eloquent\Model|null|object|static
     */
    public function getOpenID(string $code)
    {
        $url = 'https://api.weixin.qq.com/sns/jscode2session?appid='
        . config('common.app_id') .'&secret='. config('common.secret') .'&js_code='. $code .'&grant_type=authorization_code';

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);

        $content = json_decode(curl_exec($ch), true);

        curl_close($ch);
        return $this->getUserByOpenID($content);
    }

    /**
     * get user by open_id
     *
     * @param array $data
     * @return array|\Illuminate\Database\Eloquent\Model|null|object|static
     */
    private function getUserByOpenID(array $data)
    {
        $user = User::query()->where('open_id', $data['openid'])->first();

        if (!$user) {
            $time = now()->addHour(2);
            Cache::put($data['openid'], $data['session_key'], $time);
            return ['openID' => $data['openid']];
        }
        $user->token = $user->createToken('Authorization')->accessToken;

        return $user;
    }

    /**
     * bind user openID
     *
     * @param string $phone
     * @param string $openID
     * @param array $data
     * @return AuthRepository|\Illuminate\Database\Eloquent\Model|null|object
     */
    public function bindOpenID(string $phone, string $openID, array $data)
    {
        $user = $this->getUserByPhone($phone);
        if (!$user) {
            throw new BusinessException(BusinessException::PARAMETER_ERROR, '该手机号不存在', 422);
        }

        if (!$user->is_able) {
            throw new BusinessException(BusinessException::PARAMETER_ERROR, '你已经被禁止登陆了,如有疑问请联系系统管理员', 422);
        }
        $user->nike_name = $data['nickName'] ?? '';
        $user->avatar = $data['avatarUrl'] ?? '';
        $user->open_id = $openID;
        $user->save();

        $user->token = $user->createToken('Authorization')->accessToken;

        return $user;
    }
}